package com.hycloud.cloudstack.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hycloud.cloudstack.common.CloudstackApi;
import com.hycloud.cloudstack.model.SvrOffering;
import com.hycloud.cloudstack.service.SvrOfferingService;

@Service
public class SvrOfferingServiceImpl implements SvrOfferingService {

	@Autowired
	private CloudstackApi cloudstackApi;

	@Override
	public List<SvrOffering> listSvrOffering() throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		String command = "listServiceOfferings";
		params.put("command", command);
		String result = cloudstackApi.api(params);
		return null;
	}

	@Override
	public boolean exists(String name) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		String command = "listServiceOfferings";
		params.put("command", command);
		params.put("name", name);
		Map<String, Object> result = cloudstackApi.mapData(params);
		Integer count = (Integer) result.get("count");
		return count != null && count > 0;
	}

	@Override
	public SvrOffering findByName(String name) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		String command = "listServiceOfferings";
		params.put("command", command);
		params.put("name", name);
		List list = cloudstackApi.api(params, "serviceoffering", List.class);
		if(list!=null&&!list.isEmpty()){
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readValue(mapper.writeValueAsString(list.get(0)), SvrOffering.class);
		}
		return null;
	}
	
	@Override
	public SvrOffering createSvrOffering(SvrOffering svrOffering) throws Exception {
		Map<String, String> params = new HashMap<String, String>();
		String command = "createServiceOffering";
		params.put("command", command);
		params.put("name", svrOffering.getName());
		params.put("displaytext", svrOffering.getName());
		params.put("cpuspeed", "500");
		params.put("memory", svrOffering.getMemory().toString());
		params.put("cpunumber", svrOffering.getCpunumber().toString());
		return cloudstackApi.api(params, "serviceoffering", SvrOffering.class);
	}
	

}
